<template>
  <!--#region 比较操作符选项-->
  <el-popover
    ref="compareSymbolPickerRef"
    :virtual-ref="dynamicRef"
    :visible="compareSymbolPickerVisible"
    :show-arrow="false"
    width="160px"
    @hide="onHide"
  >
    <div id="compare-symbol-picker">
      <ul>
        <li
          v-for="compareSymbol in SelectableCompareSymbol[compareDataType]"
          class="flex items-center gap-x-2 py-2 px-4 rounded-md hover:bg-gray-200 text-lg"
          :key="compareSymbol"
          @click="onPickCompareSymbol(compareSymbol)"
        >
          <div class="select-none">
            <i
              :class="[
								'i-lucide-check',
								modelValue === compareSymbol ? 'opacity-100' : 'opacity-0'
							]"
            />
            {{
              CompareSymbolLabel[compareSymbol][compareDataType] ??
              CompareSymbolLabel[compareSymbol].default
            }}
          </div>
        </li>
      </ul>
    </div>
  </el-popover>
  <!--#endregion-->
</template>
<script setup lang="ts">
import {
  CompareSymbolLabel,
  SelectableCompareSymbol,
  promiseResolver,
  type PromiseResolver
} from '../lib'
import type { ColumnType, TCompareSymbol } from '../types'
import { ref, type Ref } from 'vue'
import { useToggle } from "@vueuse/core";

const props = withDefaults(
  defineProps<{
    clearModelValueWhenHide?: boolean
  }>(),
  {
    clearModelValueWhenHide: false
  }
)
const emit = defineEmits<{
  pick: [ compareSymbol: TCompareSymbol ]
}>()

const compareSymbolPickerRef = ref()
const dynamicRef: Ref<HTMLElement | null> = ref(null)

const compareDataType: Ref<ColumnType> = ref('text')
const setCompareDataType = (dataType: ColumnType) => {
  compareDataType.value = dataType
}

const [ compareSymbolPickerVisible, toggleCompareSymbolPickerVisible ] =
  useToggle(false)

const setVirtualRef = (virtualRef: HTMLElement | null): void => {
  dynamicRef.value = virtualRef
}

const modelValue = defineModel<TCompareSymbol | null>({
  required: false
})
const setModelValue = (value: TCompareSymbol | null) => {
  modelValue.value = value
}

let resolver: PromiseResolver<TCompareSymbol>
const pick = () => {
  resolver = promiseResolver<TCompareSymbol>()
  return resolver.promise
}

const onPickCompareSymbol = (compareSymbol: TCompareSymbol) => {
  modelValue.value = compareSymbol
  emit('pick', compareSymbol)
  resolver && resolver.resolve(compareSymbol)
}
const onHide = () => {
  if (props.clearModelValueWhenHide) {
    setModelValue(null)
  }
  resolver && resolver.reject(true)
  setVirtualRef(null)
}
defineExpose({
  setVirtualRef,
  toggleVisible: toggleCompareSymbolPickerVisible,
  setCompareDataType,
  setModelValue,
  pick
})
</script>
